package com.gjy.concurrency.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2022-12-13 11:03:52
 */
public class CountDownLatchTest {

    private static final Logger logger = LoggerFactory.getLogger(CountDownLatchTest.class);

    private static final CountDownLatch COUNT_DOWN_LATCH
            = new CountDownLatch(2);

    public static void main(String[] args) throws InterruptedException {
       /* Thread t1 = new Thread(new T1("t1", COUNT_DOWN_LATCH));
        Thread t2 = new Thread(new T1("t2", COUNT_DOWN_LATCH));
        t1.start();
        t2.start();*/
        ExecutorService pool = Executors.newFixedThreadPool(2);
        pool.execute(new T1("hh1", COUNT_DOWN_LATCH));
        pool.execute(new T1("hh2", COUNT_DOWN_LATCH));
        logger.info("1");
        COUNT_DOWN_LATCH.await();
        pool.shutdown();
        logger.info("2");
    }

    private static class T1 implements Runnable {
        private final String name;
        private final CountDownLatch countDownLatch;

        private T1(String name, CountDownLatch countDownLatch) {
            this.name = name;
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            logger.info("{}", name);
            try {
                TimeUnit.SECONDS.sleep(1);
                countDownLatch.countDown();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
